package com.ruhua.java.api;

import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import com.ruhua.java.core.LocalUser;
import com.ruhua.java.core.interceptors.ScopeLevel;
import com.ruhua.java.dao.Order;
import com.ruhua.java.dto.OrderDTO;
import com.ruhua.java.exception.ErrException;
import com.ruhua.java.exception.HttpException;
import com.ruhua.java.exception.NotFoundException;
import com.ruhua.java.exception.TrowException;
import com.ruhua.java.lib.LinWxNotify;
import com.ruhua.java.logic.OrderCheck;
import com.ruhua.java.repository.OrderRepository;
import com.ruhua.java.service.OrderService;
import com.ruhua.java.service.WxPaymentNotifyService;
import com.ruhua.java.service.WxPaymentService;
import com.ruhua.java.vo.GoodsVO;
import com.ruhua.java.vo.OrderListVO;
import com.ruhua.java.vo.ResVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import static com.ruhua.java.util.CommonUtil.toJsonString;


@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private WxPaymentService wxPaymentService;

    @Autowired
    private WxPaymentNotifyService wxPaymentNotifyService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderRepository orderRepository;


    @PutMapping("/user/del_order")
    @ScopeLevel()
    public ResVO<String> del_order(@RequestParam Long id){
        Long uid = LocalUser.getUser().getId();
        Optional<Order> op_order=orderRepository.findByOrderId(id);
        Order order=op_order.orElseThrow(()-> new ErrException("订单不存在"));
        try {
            if(!uid.equals(order.getUserId())) {
               throw new ErrException("订单不存在");
            }
            orderRepository.deleteById(id);
        } catch(HttpException e){
            throw new TrowException("订单错误：" + e.getMsg());
        }
        return ResVO.go();
    }

    @GetMapping("/user/not_order")
    @ScopeLevel()
    public ResVO<List> orderList(){
        Long uid = LocalUser.getUser().getId();
        Mapper mapper = DozerBeanMapperBuilder.buildDefault();List<Order> list=orderService.MyNotPayOrder(uid);
        List<OrderListVO> vos = new ArrayList<>();  list.forEach(s->{
            OrderListVO vo = mapper.map(s,OrderListVO.class);
            vos.add(vo);
        });
        return ResVO.go(vos);
    }

    @GetMapping("/user/all_order")
    @ScopeLevel()
    public ResVO<List> orderPayList(){
        Long uid = LocalUser.getUser().getId();
        System.out.println("uid:"+uid);
        List<Order> list=orderService.MyPayOrder(uid);
        return ResVO.go(list);
    }

    @PostMapping("/admin/get_order")
    public ResVO<List> orderAll(){
        List<Order> list=orderService.findAll();
        return ResVO.go(list);
    }

    @GetMapping("/user/get_order_one")
    @ScopeLevel(4)
    public ResVO<Order> get_order(@RequestParam Long id){
        Order item=orderService.getById(id);
        if(item == null){
            throw new NotFoundException(10001);
        }
        return ResVO.go(item);
    }


    double money=0;
    @PostMapping("/get_order_money")
    @ScopeLevel()
    public ResVO<Map<String, Object>> get_order_money(@RequestBody List<Map<String,Long>> dto) {
        double total=0;
        if(dto!=null && dto.size()>0){
            dto.forEach(s->{
                int num=Integer.parseInt(s.get("num").toString());
                double price=Double.valueOf(s.get("price"));
                this.money += num*price;
            });
            total=this.money;
            this.money=0;
        }
        Map<String, Object> data=new HashMap<>();
        data.put("total_money",total);
        data.put("reduce",0);
        return ResVO.go(data);
    }



    @PostMapping("/create")
    @ScopeLevel()
    @Transactional
    public ResVO<Map<String,Long>> create_order(@RequestBody @Validated OrderDTO orderDTO) {
        try{
            System.out.println("111");
            Long uid = LocalUser.getUser().getId(); OrderCheck orderCheck = this.orderService.check(orderDTO);
            Long orderId=this.orderService.createOrder(uid,orderDTO);   this.orderService.createOrderSku(orderId,orderCheck.getSkuList(),orderCheck.getOrderNumlist());Map<String,Long> map=new HashMap<>();
            map.put("id",orderId);
            return ResVO.go(map);
        }catch(HttpException e){
            throw new TrowException("订单错误：" + e.getMsg());
        }
    }


    @PostMapping("/pay/pre_order")
    @ScopeLevel()
    public ResVO<Map<String, String>> preWxOrder(@RequestParam Long id) {
        System.out.println("idsx:" + id);
        Map<String, String> miniPayParams = wxPaymentService.preOrder(id);
        return ResVO.go(miniPayParams);
    }


    @RequestMapping("/wx/notify")
    public String payCallback(HttpServletRequest request,
                              HttpServletResponse response) {
        System.out.println("进入回调");
        InputStream s;
        try {
            s = request.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            return LinWxNotify.fail();
        }
        String xml;
        xml = LinWxNotify.readNotify(s);
        try{
            this.wxPaymentNotifyService.processPayNotify(xml);
        }
        catch (Exception e){
            return LinWxNotify.fail();
        }
        return LinWxNotify.success();
    }


    @GetMapping("/num/{num}")
    public Order get_order_name(@PathVariable String num){
        Optional<Order> optionalCategory=orderService.getByName(num);
        return optionalCategory.orElseThrow(()-> new NotFoundException(10001));
    }

    @PutMapping("/admin/del_order")
    @Transactional
    public ResVO<String> del_article(@RequestParam Long id){

        orderService.delItem(id);
        return ResVO.go();
    }

    @GetMapping("/admin/edit_pay")
    public ResVO<String> edit_pay(@RequestParam Long id){
        Optional<Order> item=orderService.findByOrderId(id);
        Order order = item.orElseThrow( () -> new NotFoundException(10009));
        if(order.getPaymentState()!=0){
            throw new TrowException("已支付状态错误");
        }
        order.setPaymentState(1);
        orderRepository.save(order);
        return ResVO.go();
    }

    @GetMapping("/admin/edit_courier")
    public ResVO<String> edit_courier(@RequestParam Long id){
        Optional<Order> item=orderService.findByOrderId(id);
        Order order = item.orElseThrow( () -> new NotFoundException(10009));
        if(order.getShipmentState()!=0){
            throw new TrowException("发货状态错误");
        }
        order.setShipmentState(1);
        orderRepository.save(order);
        return ResVO.go();
    }

    @PutMapping("/user/receive")
    public ResVO<String> user_receive(@RequestParam Long id){
        Optional<Order> item=orderService.findByOrderId(id);
        Order order = item.orElseThrow( () -> new NotFoundException(10009));
        if(order.getShipmentState()!=1){
            throw new TrowException("发货状态错误");
        }
        order.setShipmentState(2);
        orderRepository.save(order);
        return ResVO.go();
    }
}
